<template>
  <div class="overTime">
    <van-nav-bar
      title="加班申请"
      left-arrow
      @click-left="goBackHandle"
      :fixed="true"
      :border="false"
      :safe-area-inset-top="true"
      style="padding-top: 0px"
    >
    </van-nav-bar>
    <div class="dataContent">
      <div>
        <div class="contentTop"></div>
        <van-form>
          <van-field
            readonly
            clickable
            border
            name="calendar"
            required
            :value="overTimeInfo.startTime"
            label="开始时间"
            placeholder="请选择开始时间"
            input-align="right"
            @click="clickShowCalendar(1)"
            :rules="[{ required: true, message: '请选择开始时间' }]"
          >
            <template #extra>
              <van-icon class="extra" name="arrow-down" size="18" />
            </template>
          </van-field>
          <van-field
            readonly
            clickable
            name="calendar"
            required
            :value="overTimeInfo.finishTime"
            label="结束时间"
            placeholder="请选择结束时间"
            input-align="right"
            @click="clickShowCalendar(2)"
            :rules="[{ required: true, message: '请选择结束时间' }]"
          >
            <template #extra>
              <van-icon class="extra" name="arrow-down" size="18" />
            </template>
          </van-field>
          <!-- <van-field
            readonly
            clickable
            name="calendar"
            :value="overTimeInfo.overTimeLength"
            label="加班时长"
            input-align="right"
          >
            <template #extra>
              <div class="extra" name="extra">小时</div>
            </template>
          </van-field> -->
          <van-field
            readonly
            autocomplete="off"
            name="calendar"
            :value="overTimeInfo.overTimeLength"
            label="加班时长"
            input-align="right"
          >
            <template #extra>
              <div class="extra" name="extra">小时</div>
            </template>
          </van-field>
          <van-action-sheet
            v-model="showCalendar"
            show-toolbar
            :lock-scroll="false"
            :round="false"
            :lazy-render="false"
            :close-on-click-overlay="true"
          >
            <van-tabs
              v-model="active"
              :line-width="lineWidth"
              line-height="2px"
              color="#999"
              @click="onClick"
            >
              <van-tab :title="titleTime">
                <van-calendar
                  v-if="checkCalendar === 1"
                  :default-date="defaultDate"
                  :show-confirm="false"
                  :poppable="false"
                  :round="false"
                  :show-title="false"
                  :show-subtitle="false"
                  @select="onSelect"
                  color="#777"
                  row-height="40"
                  :min-date="new Date('2023/01/01')"
                />
                <van-calendar
                  v-else
                  :default-date="defaultDate"
                  :show-confirm="false"
                  :poppable="false"
                  :round="false"
                  :show-title="false"
                  :show-subtitle="false"
                  @select="onSelect"
                  :min-date="maxdate"
                  :max-date="maxdate"
                  color="#777"
                  row-height="40"
                />
              </van-tab>
              <van-tab :title="titleColumns">
                <van-datetime-picker
                  v-if="checkCalendar === 1"
                  type="time"
                  v-model="currentTime1"
                  :show-toolbar="false"
                  @change="onChange"
                />
                <van-datetime-picker
                  v-else
                  type="time"
                  v-model="currentTime"
                  :show-toolbar="false"
                  @change="onChange"
                  :min-hour="minhour"
                  :min-minute="minminute"
                />
              </van-tab>
              <template #nav-right>
                <span class="sheetConfirm" @click="sheetConfirm">确认</span>
              </template>
            </van-tabs>
          </van-action-sheet>
          <div class="contentTop"></div>
          <van-field
            v-model="overTimeInfo.overReason"
            rows="3"
            maxlength="100"
            show-word-limit
            required
            autocomplete="off"
            error-message-align="left"
            type="textarea"
            class="textarea"
            label="加班事由"
            placeholder="请输入加班事由"
            :rules="[{ required: true }]"
          />
          <div class="footer">
            <van-button type="default" @click="submit">提交</van-button>
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import { FailFN, SuccesFN } from '@/DceMessage'
import { Toast } from 'vant'
import backMixin from '@/backMixin'
export default {
  name: 'overTime',
  mixins: [backMixin],
  data() {
    return {
      overTimeInfo: {
        startTime: '', //表单开始时间
        finishTime: '', //表单结束时间
        overTimeLength: '', //表单加班时长
        overReason: '' //表单加班事由
      },
      showCalendar: false, //是否展示日历弹窗
      active: 2, //tab栏默认选中日历
      defaultDate: new Date(), //默认选中日期
      titleTime: '', //日历标题
      titleColumns: '', //默认选中12:00
      currentTime: '',
      currentTime1: '',
      lineWidth: '90px', //tab栏下横线默认长度
      clickForm: '', //点击的是开始时间还是结束时间
      sum: 0,
      starttime: '',
      finishtime: '',
      sumarr: [],
      checkCalendar: 1, //获取开始日期还是结束日期
      maxdate: new Date(), //默认最大日期
      minhour: '',
      minminute: '',
      dateall: [], //存储所有区间日期
      datetype: 0, //判断节假日 0：非节假日 1：节假日
      paramsData: {}
    }
  },
  created() {
    if (
      this.$route.params &&
      JSON.parse(window.localStorage.getItem('askOffOrOverTimeData'))
    ) {
      console.log('进入判断')
      this.paramsData = this.$route.params
    }
    if (this.paramsData && this.paramsData.StartDate) {
      this.overTimeInfo.startTime = this.paramsData.StartDate
      this.overTimeInfo.finishTime = this.paramsData.EndDate
      this.overTimeInfo.overTimeLength = this.paramsData.Duration
      this.overTimeInfo.overReason = this.paramsData.Reason
    }
  },
  methods: {
    // tab栏点击事件
    onClick() {
      if (this.active == 0) {
        console.log('000')
        this.lineWidth = '90px'
      } else {
        console.log('111')
        this.lineWidth = '40px'
      }
    },
    // 点击表单显示弹窗
    clickShowCalendar(val) {
      this.checkCalendar = val

      if (val === 1 || this.overTimeInfo.startTime) {
        this.showCalendar = true
      } else {
        this.showCalendar = false
        Toast.fail('请先选择开始时间')
      }
      this.active = 0
      this.lineWidth = '90px'

      // let strDay = date.getDay()
      // let weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      if (val === 1 && this.overTimeInfo.startTime) {
        this.titleTime = this.overTimeInfo.startTime.substr(
          0,
          this.overTimeInfo.startTime.length - 6
        )
        this.titleColumns = this.overTimeInfo.startTime.slice(
          this.overTimeInfo.startTime.length - 5,
          this.overTimeInfo.startTime.length
        )

        this.defaultDate = new Date(
          this.overTimeInfo.startTime.substr(
            0,
            this.overTimeInfo.startTime.length - 6
          )
        )
        this.maxdate = new Date(
          this.overTimeInfo.startTime.substr(
            0,
            this.overTimeInfo.startTime.length - 6
          )
        )
        setTimeout(() => {
          this.currentTime1 = this.titleColumns
        }, 300)
      } else if (val === 2 && this.overTimeInfo.finishTime) {
        this.titleTime = this.overTimeInfo.finishTime.substr(
          0,
          this.overTimeInfo.finishTime.length - 6
        )

        console.log('选中后日期', this.titleTime)
        this.titleColumns = this.overTimeInfo.finishTime.slice(
          this.overTimeInfo.finishTime.length - 5,
          this.overTimeInfo.finishTime.length
        )
        this.currentTime = this.titleColumns
        this.defaultDate = new Date(
          this.overTimeInfo.finishTime.substr(
            0,
            this.overTimeInfo.finishTime.length - 6
          )
        )
        this.maxdate = new Date(
          this.overTimeInfo.startTime.substr(
            0,
            this.overTimeInfo.startTime.length - 6
          )
        )
      } else {
        let date = new Date()
        let year = date.getFullYear() //获取完整的年份(4位,1970-????)
        let month = date.getMonth() + 1
        month < 10 ? (month = '0' + month) : month
        let strDate = date.getDate()
        strDate < 10 ? (strDate = '0' + strDate) : strDate
        this.titleTime = year + '-' + month + '-' + strDate
        // 日历默认选中当前日期
        this.defaultDate = new Date()
        // tab上显示的几点与选中的保持一致，默认是当前时间点

        let hours = date.getHours() // 小时
        hours < 10 ? (hours = '0' + hours) : hours
        let minutes = date.getMinutes() // 分钟
        minutes < 10 ? (minutes = '0' + minutes) : minutes
        this.titleColumns = hours + ':' + minutes
        this.currentTime1 = hours + ':' + minutes
      }

      if (val == 1) {
        // 点击的是开始时间表单项
        this.clickForm = 1
      } else {
        // 点击的是结束时间表单项
        this.clickForm = 2
      }
    },
    // 选中日期，继续选择几点
    onSelect(date) {
      console.log(date)
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      month < 10 ? (month = '0' + month) : month
      let strDate = date.getDate()
      strDate < 10 ? (strDate = '0' + strDate) : strDate
      // let strDay = date.getDay()
      // let weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      this.titleTime = year + '-' + month + '-' + strDate
      this.showCalendar = true
      this.active = 1
      this.lineWidth = '40px'
    },
    // 选择时间change事件
    onChange(picker, value, index) {
      console.log('picker>>>>>>', picker.getValues())
      let changeValue = picker.getValues()
      this.titleColumns = changeValue[0] + ':' + changeValue[1]
      if (this.checkCalendar === 1) {
        this.currentTime1 = changeValue[0] + ':' + changeValue[1]
        this.currentTime = changeValue[0] + ':' + changeValue[1]
      } else {
        this.currentTime = changeValue[0] + ':' + changeValue[1]
      }
    },
    // 点击弹窗的确认按钮
    sheetConfirm() {
      // 弹窗关闭
      this.showCalendar = false
      console.log(this.titleTime)
      console.log(this.titleColumns)
      if (this.clickForm == 1) {
        this.overTimeInfo.startTime = this.titleTime + ' ' + this.titleColumns
        this.starttime = this.titleTime
        this.overTimeInfo.finishTime = this.titleTime + ' ' + this.titleColumns
        this.minhour = this.currentTime1.substring(
          0,
          this.currentTime1.indexOf(':')
        )
        this.minminute = this.currentTime1.substring(
          this.currentTime1.indexOf(':') + 1
        )
      } else if (this.clickForm == 2) {
        this.overTimeInfo.finishTime = this.titleTime + ' ' + this.titleColumns
        this.finishtime = this.titleTime
      }
      // 如果开始时间和结束时间都有值，得到加班时长
      if (this.overTimeInfo.finishTime && this.overTimeInfo.startTime) {
        let finishTime = this.overTimeInfo.finishTime.replace(/\-/g, '/')
        let startTime = this.overTimeInfo.startTime.replace(/\-/g, '/')
        let finishTimeTime = new Date(finishTime).getTime() / (1000 * 3600)
        let startTimeTime = new Date(startTime).getTime() / (1000 * 3600)

        // this.getYearAndMonthAndDay(this.starttime, this.finishtime)
        console.log(finishTimeTime)

        let overTimeLength = (finishTimeTime - startTimeTime).toFixed(2)

        setTimeout(() => {
          this.overTimeInfo.overTimeLength = overTimeLength
            .toString()
            .includes('.00')
            ? Math.floor(overTimeLength)
            : overTimeLength

          // console.log(finishTimeTime)
          // console.log(startTimeTime)
          // console.log(this.overTimeInfo.overTimeLength)
          // this.sum = 0
        }, 500)
      }
    },
    //获取起止日期区间所有日期，并且计算出含非工作日数量
    getYearAndMonthAndDay(start, end) {
      var date_all = [],
        i = 0
      var startTime = new Date(start)
      var endTime = new Date(end)
      while (endTime.getTime() - startTime.getTime() >= 0) {
        var year = startTime.getFullYear()
        var month =
          (startTime.getMonth() + 1).toString().length == 1
            ? '0' + (startTime.getMonth() + 1).toString()
            : (startTime.getMonth() + 1).toString()
        var day =
          startTime.getDate().toString().length == 1
            ? '0' + startTime.getDate()
            : startTime.getDate()
        date_all[i] = year + '-' + month + '-' + day
        startTime.setDate(startTime.getDate() + 1)
        i += 1
      }
      console.log('日期区间', date_all)
      this.sumarr = []
      this.dateall = []

      this.$axios({
        url: `/attendance-api/isholiday`,
        method: 'post',
        data: {
          dateList: date_all.toString()
        }
      }).then(res => {
        this.dateall = res.data.Object
        console.log('节假日', res)

        this.sumarr = this.dateall.filter(item => item.IsHoliday == true)
        console.log('循环结果', this.sumarr)
      })
    },
    // 点击提交按钮
    submit() {
      console.log('点击提交按钮')
      console.log(this.overTimeInfo)
      if (
        this.overTimeInfo.startTime !== '' &&
        this.overTimeInfo.finishTime !== '' &&
        this.overTimeInfo.overReason !== '' &&
        this.overTimeInfo.overTimeLength != 0
      ) {
        this.$axios({
          url: '/attendance-api/application-add',
          method: 'POST',
          data: {
            applicantId: JSON.parse(localStorage.getItem('attendance-records'))
              .id,
            deptId: JSON.parse(localStorage.getItem('attendance-records'))
              .deptId,
            startDate: this.overTimeInfo.startTime + ':00',
            endDate: this.overTimeInfo.finishTime + ':00',
            reason: this.overTimeInfo.overReason,
            duration: this.overTimeInfo.overTimeLength,
            type: '0',
            applicationType: '1'
          }
        }).then(res => {
          console.log('ddas', res)
          if (res) {
            SuccesFN(res.data.Message)
            localStorage.setItem('isRefreshOver', 1)

            if (
              this.paramsData !== {} &&
              JSON.parse(window.localStorage.getItem('askOffOrOverTimeData'))
            ) {
              this.cheXiao()
            }
            localStorage.removeItem('askOffOrOverTimeData')
            setTimeout(() => {
              this.$router.replace('/workbench')
            }, 1000)
          }
        })
      } else {
        if (this.overTimeInfo.overTimeLength == '0') {
          FailFN('加班时长不能为0')
        }
      }
    },
    cheXiao() {
      this.$axios({
        url: '/attendance-api/application-cancel',
        method: 'POST',
        data: {
          applicationId: this.paramsData.Id,
          status: 3
        }
      }).then(res => {})
    },
    // 点击返回按钮
    goBackHandle() {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.overTime ::v-deep {
  margin: 0;
  padding: 0;
  background-color: #f5f5f5;

  .van-nav-bar__arrow {
    font-size: 18px;
    color: #000;
  }
  .van-nav-bar__content {
    .van-nav-bar__title {
      font-size: 18px;
    }
  }
  .dataContent {
    .contentTop:first-child {
      margin-top: 56px;
    }
    .van-field {
      padding: 10px 16px;
    }

    .overTime::after {
      border: 0 !important;
    }
    .textarea {
      display: inline-block;
      .van-field__control--right {
        text-align: left;
      }
    }
    .textarea::after {
      border: 0 !important;
    }
  }
  input.van-field__control::-webkit-input-placeholder {
    color: #c8c9cc;
  }
  .van-field__error-message {
    text-align: right;
  }
  .van-icon {
    padding-top: 3px;
  }
  .extra {
    margin-left: 5px;
  }
  .van-tab {
    font-size: 16px;
  }
  .van-tabs__line {
    transition-duration: 0s !important;
  }
  .van-tabs__wrap {
    position: sticky;
    top: 0;
    // border-bottom: 1px solid #f5f5f5;
    z-index: 998;
  }
  .van-tabs__nav {
    background-color: #eee;
  }
  .sheetConfirm {
    line-height: 44px;
    padding: 0 10px;
    // margin-left: 40px;
    color: #006dff;
  }
  .van-calendar {
    height: 300px;
  }
  .van-picker {
    height: 300px;
  }
  .van-calendar__header {
    position: sticky;
    top: 43px;
    // margin-top: -1px;
    background-color: #fff;
    -webkit-appearance: none;
    box-shadow: 0;
    -webkit-box-shadow: 0;
    z-index: 997;
  }
  .van-action-sheet {
    display: flex;
    // width: 100%;
    justify-content: space-between;
    .button {
      display: inline-block;
      // width: 20%;
    }
  }
  .footer {
    position: fixed;
    bottom: 0;
    display: flex;
    width: 100%;
    .van-button {
      flex: 1;
      margin: 10px 16px;
      background-color: #006dff;
      color: #fff;
      font-size: 16px;
      border-radius: 10px;
      border: 0;
    }
  }
}
</style>
